#coding:utf-8
from django.views.decorators.cache import cache_page,never_cache,cache_control
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from django.contrib import auth,messages
from settings import NOTE_PAGE_SIZE,TOPIC_PAGE_SIZE
from utils import *
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.cache import cache
from models import *
from forms import *
from urllib import urlencode
from django.utils.html import escape
from django.db import transaction    


@never_cache
def index(request):
    current_user = request.user
    print dir(current_user)
    if current_user.is_authenticated():
        user_profile = current_user.get_profile()
        follows = user_profile.follows.select_related('user')
        mygroups = user_profile.join_groups.all()
        notes = Note.objects.extra(
            select={
                'user_image':'select image from  mobeir_userprofile where mobeir_note.user_id = mobeir_userprofile.user_id',    
            }
        ).order_by("-last_update").select_related('user')[0:1000]
        paginator =  Paginator(notes,NOTE_PAGE_SIZE)
        
        try:
            cnotes = paginator.page(get_page(request))
        except (EmptyPage, InvalidPage):
            cnotes = paginator.page(paginator.num_pages)
    else:
        return HttpResponseRedirect("/group/all/")
         
    debug_sql('group.index')
    return render_to_response('group.html', locals())

def all_group(request):
    header = request.GET.get("go") or "all"
    if header == "all":
        groups = Group.objects.all_group()[0:30]
    if header == "device":
        groups = Group.objects.all_group()[0:30]
    if header == "app":
        groups = Group.objects.all_group()[0:30]
    if header == "develop":
        groups = Group.objects.all_group()[0:30]                        
    
    hot_topics =  Topic.objects.hot_topics()
    return render_to_response('group_all.html', locals())    

@never_cache
def group(request,gid):
    current_user = request.user
    if current_user.is_authenticated():
        user_profile = current_user.get_profile()
        follows = user_profile.follows.select_related('user')
        mygroups = user_profile.join_groups.all()[0:12]
    
    group = Group.objects.get(id=gid)
    has_user = current_user.is_authenticated() and \
               group.user_join_groups.filter(user=current_user).count()\
               and "true" or "false"
    join_users = group.user_join_groups.all()[0:20]
    join_count = group.user_join_groups.count()
    topics_tmp = Topic.objects.group_topics(group)
    paginator =  Paginator(topics_tmp,TOPIC_PAGE_SIZE)
    
    try:
        topics = paginator.page(get_page(request))
    except (EmptyPage, InvalidPage):
        topics = paginator.page(paginator.num_pages)   
        
    debug_sql('group.index')
    return render_to_response('group_one.html', locals())

def join_group(request):
    gid = request.GET.get('groupid')
    if not request.user.is_authenticated():
        return  HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/join/?groupid=%s'%gid}))   
    group = Group.objects.get(pk=gid)
    if group.user_join_groups.filter(user=request.user).count()==0:
        prifile = request.user.get_profile()
        prifile.join_groups.add(group)
        prifile.save()
    return HttpResponseRedirect("/group/%s"%gid)
    


@never_cache
@transaction.commit_on_success    
def add_group(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/add/'}))    
    
    if request.method == 'POST':
        form = GroupForm(request.POST)

        if form.is_valid():
            cd = form.cleaned_data       
            #处理标签
            categorys  = cd.get('categorys','').split(',')
            categorys.extend(cd.get("group_type",[]))
            gtags = []
            for tag in categorys:
                try:
                    gcy = GroupCategory.objects.get(name=tag)
                except:
                    gcy = GroupCategory()
                    gcy.name = tag
                    gcy.save()
                    gtags.append(gcy)
                    
            group = Group.objects.create()
            group.name = (cd['name'])
            group.privacy = cd['privacy']
            group.summary = cd['summary']
            group.creater = request.user
            group.admins.add(request.user)
            group.image = "images/default_group.jpg"
            group.save()
            
            for t in gtags:
                group.categorys.add(t)    
            group.save()        
            
            title = u"申请圈子请求已经提交,请耐心等待审核通过"
            message = title
            backurl = "/group/"
            return render_to_response("redirect.html",locals())

        
        
    elif request.method == 'GET':
        form = GroupForm()
        
    return render_to_response('add_group.html',locals())    
        
        
@never_cache
def my_group(request):
    current_user = request.user
    if not current_user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/my/'})) 
    
    if current_user.is_authenticated():
        user_profile = current_user.get_profile()
        follows = user_profile.follows.select_related('user')
        mygroups = user_profile.join_groups.all()[0:12]
    
    
    topics_tmp = Topic.objects.extra(
    select={
        'replies_count': 'select count(*) from mobeir_topic_comments where mobeir_topic_comments.topic_id = mobeir_topic.id',
        },
    ).select_related('user').order_by('-last_update')
    
    

    paginator =  Paginator(topics_tmp,TOPIC_PAGE_SIZE)
    
    try:
        topics = paginator.page(get_page(request))
    except (EmptyPage, InvalidPage):
        topics = paginator.page(paginator.num_pages)    
        
    debug_sql('group.my_group')
    header = "my"
    return render_to_response('group_my.html', locals())  

@never_cache
def my_topics(request):
    current_user = request.user
    if not current_user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/topic/my/'}))    
    
    if current_user.is_authenticated():
        user_profile = current_user.get_profile()
        follows = user_profile.follows.select_related('user')
        mygroups = user_profile.join_groups.all()[0:12]
      
    paginator =  Paginator(Topic.objects.my_topics(request.user),TOPIC_PAGE_SIZE)
    try:
        topics = paginator.page(get_page(request))
    except (EmptyPage, InvalidPage):
        topics = paginator.page(paginator.num_pages)    
    debug_sql('group.my_topics')    
    header = "topics"
    return render_to_response('group_my.html', locals())  

@never_cache
def my_replies(request):
    current_user = request.user
    if not current_user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/replies/my/'}))    
    if current_user.is_authenticated():
        user_profile = current_user.get_profile()
        follows = user_profile.follows.select_related('user')
        mygroups = user_profile.join_groups.all()[0:12]
    
    profile = user_profile
    
    topics_tmp = profile.retopics.extra(
        select={
             'replies_count': '''
             select count(*) from mobeir_topic_comments 
             where mobeir_topic_comments.topic_id = mobeir_topic.id
             ''',
        },
    ).order_by('-last_update').select_related('user')
    paginator =  Paginator(topics_tmp,TOPIC_PAGE_SIZE)
    
    try:
        topics = paginator.page(get_page(request))
    except (EmptyPage, InvalidPage):
        topics = paginator.page(paginator.num_pages)    
    header = "replies"
    debug_sql('group.my_replies')    
    return render_to_response('group_my.html', locals())  

def post_note(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect("/login/?%s"%urlencode({'next':'/group/note/add/'}))  
    n = request.POST['note']
    if not n or len(n)<=0:
        return HttpResponseRedirect("/group/")
    
    note = Note()
    note.user = request.user
    note.content = n
    note.save()
    return HttpResponseRedirect("/group/")



def delete_note(request,id):
    if not request.user.is_authenticated():
        return HttpResponse(u"登录超时", mimetype="text/plain")
    try:
        note = Note.objects.filter(id=id,user=request.user).delete()
    except:
        return u"删除失败，请稍后再试"
    return HttpResponse("ok")








